import { getBase64, uploadToAliyunOSS } from "@/utils";
import { PlusOutlined } from "@ant-design/icons";
import { Image, Input, message, Upload, UploadFile } from "antd";
import { useEffect, useState } from "react";

const UploadImage: React.FC<{
  value?: string[];
  onChange?(v: string[]): void;
  max?: number;
  hideCheckType?: boolean;
}> = function (props) {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [fileList, setFileList] = useState<any[]>([]);
  useEffect(() => {
    setFileList(
      (props.value || []).map((url, uid) => {
        return {
          uid,
          status: "done",
          url,
        };
      })
    );
  }, [props.value]);
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );

  return (
    <>
      <Upload
        listType="picture-card"
        fileList={fileList}
        onPreview={handlePreview}
        onChange={({ fileList }) => {
          let list = fileList.filter((item) => item.status !== "error");
          let doneList = fileList
            .filter((item) => item.status == "done")
            .map((item) => item.url! || item.response);
          if (JSON.stringify(doneList) !== JSON.stringify(props.value || [])) {
            props.onChange?.(doneList);
          }

          return setFileList(list);
        }}
        accept={props.hideCheckType ? undefined : "image/*"}
        multiple={true}
        beforeUpload={(file) => {
          const isImage = file.type.startsWith("image/");
          if (!isImage && !props.hideCheckType) {
            message.error("只能上传图片文件!");
            return Upload.LIST_IGNORE; // 阻止文件加入列表
          }

          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
            message.error("图片大小必须小于 2MB!");
            return Upload.LIST_IGNORE;
          }

          return true; // 返回 true 表示文件通过验证
        }}
        customRequest={async (options) => {
          const { file, onSuccess, onError, onProgress } = options;
          uploadToAliyunOSS(file).then((res) => {
            onSuccess!(res);
          }, onError);
        }}
      >
        {fileList.length >= (props.max || 100) ? null : uploadButton}
      </Upload>
      {previewImage && (
        <Image
          wrapperStyle={{ display: "none" }}
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => setPreviewOpen(visible),
            afterOpenChange: (visible) => !visible && setPreviewImage(""),
          }}
          src={previewImage}
        />
      )}
    </>
  );
};

export const UploadOneImage: React.FC<{
  value?: string;
  onChange?(v: string): void;
  showInput?: boolean;
  hideCheckType?: boolean;
}> = function (props) {
  return (
    <>
      <UploadImage
        max={1}
        value={props.value ? [props.value] : []}
        onChange={(v) => {
          props.onChange?.(v?.[0]);
        }}
        hideCheckType={props.hideCheckType}
      />
      {props.showInput && (
        <Input
          style={{ marginTop: 3 }}
          placeholder={"请输入"}
          value={props.value}
          onChange={(e) => props.onChange?.(e.target.value)}
        />
      )}
    </>
  );
};
export default UploadImage;
